package com.ustropo.financas;

import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar.OnNavigationListener;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.ustropo.financas.categoria.CategoriaActivity;
import com.ustropo.financas.categoria.GrupoActivity;
import com.ustropo.financas.conta.ContaActivity;
import com.ustropo.financas.despesa.DespesaActivity;
import com.ustropo.financas.navigator.IMenuDrawerConstants;
import com.ustropo.financas.navigator.NavDrawerAdapter;
import com.ustropo.financas.navigator.NavDrawerItem;
import com.ustropo.financas.navigator.NavMenuItem;
import com.ustropo.financas.navigator.NavMenuSection;
import com.ustropo.financas.receita.ReceitaActivity;
import com.ustropo.financas.transferencia.TransferenciaActivity;

/**
 * Classe da aplicação principal. 
 * <p>
 * Esta classe mostra as opções principais através de um navegador lateral:
 * 	 - Contas
 * 	 - Transferências
 *   - Despesas
 *   - Receitas
 *   - Categoria
 *   - Grupos
 * <p>
 * Na tela inicial é mostrado um resumo das contas - saldo 
 * 
 * @author Fernando C. de Souza
 * @version 1.0
 * @since 25/10/2013
 */
public class MainActivity extends ActionBarActivity implements OnNavigationListener {
			
	/* variáveis */
	private NavDrawerItem[] menu;
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;
	
	/*
	 * (non-Javadoc)
	 * @see android.support.v7.app.ActionBarActivity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		// itens do menu lateral
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);
        
        // Set the adapter for the list view
        menu = new NavDrawerItem[] {
                NavMenuSection.create(IMenuDrawerConstants.MENU_SECTION_USUARIO, "Usuario"),
                NavMenuItem.create(IMenuDrawerConstants.MENU_ITEM_CONTAS, "Contas", "navdrawer_friends", false, this),
                NavMenuItem.create(IMenuDrawerConstants.MENU_ITEM_RECEITAS, "Receitas", "navdrawer_airport", false, this),
                NavMenuItem.create(IMenuDrawerConstants.MENU_ITEM_DESPESAS, "Despesas", "navdrawer_test", false, this),
        		NavMenuItem.create(IMenuDrawerConstants.MENU_ITEM_TRANSFERENCIA, "Transferências", "navdrawer_test", false, this),
        		NavMenuItem.create(IMenuDrawerConstants.MENU_ITEM_CATEGORIAS, "Categorias", "navdrawer_test", false, this),
        		NavMenuItem.create(IMenuDrawerConstants.MENU_ITEM_GRUPOS, "Grupos", "navdrawer_test", false, this),
        		NavMenuSection.create(IMenuDrawerConstants.MENU_SECTION_CONFIG, "Configurações")};
        NavDrawerAdapter adapter = new NavDrawerAdapter(getApplicationContext(), R.layout.nav_drawer_item, menu);
        mDrawerList.setAdapter(adapter);
        // Set the list's click listener
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
        
        mDrawerToggle = new ActionBarDrawerToggle(
                this,                  /* host Activity */
                mDrawerLayout,         /* DrawerLayout object */
                R.drawable.ic_drawer,  /* nav drawer icon to replace 'Up' caret */
                R.string.drawer_open,  /* "open drawer" description */
                R.string.drawer_close  /* "close drawer" description */
                ) {

            /** Called when a drawer has settled in a completely closed state. */
            public void onDrawerClosed(View view) {
                getSupportActionBar().setTitle(getTitle());
            }

            /** Called when a drawer has settled in a completely open state. */
            public void onDrawerOpened(View drawerView) {
            	getSupportActionBar().setTitle(getTitle());
            }
        };

        // Set the drawer toggle as the DrawerListener
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);		

	}


	/*
	 * (non-Javadoc)
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu){
		getMenuInflater().inflate(R.menu.activity_main_menu, menu);
			
		return super.onCreateOptionsMenu(menu);
	}

	/*
	 * (non-Javadoc)
	 * @see android.support.v7.app.ActionBar.OnNavigationListener#onNavigationItemSelected(int, long)
	 */
	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
		// TODO Auto-generated method stub
		return false;
	}
	
	/*
	 * (non-Javadoc)
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Pass the event to ActionBarDrawerToggle, if it returns
        // true, then it has handled the app icon touch event
        if (mDrawerToggle.onOptionsItemSelected(item)) {
          return true;
        }
        
        // Handle your other action bar items...      
        return super.onOptionsItemSelected(item);
    }
	
    /*
     * (non-Javadoc)
     * @see android.app.Activity#onPostCreate(android.os.Bundle)
     */
    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }
    
    /*
     * (non-Javadoc)
     * @see android.support.v7.app.ActionBarActivity#onConfigurationChanged(android.content.res.Configuration)
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }
    
	/**
	 * 
	 * @param v
	 */
	public void onMenuItemClick(MenuItem item){
		//Intent i = new Intent(getApplicationContext(), MainActivity.class);
		//startActivity(i);
	}
    
	/**
	 * 
	 * @author Fernando C. de Souza
	 * @version 1.0
	 * @since 08/10/2013
	 */
	private class DrawerItemClickListener implements ListView.OnItemClickListener {

		/*
		 * (non-Javadoc)
		 * @see android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget.AdapterView, android.view.View, int, long)
		 */
		@Override
	    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
	        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
	        Fragment frag = null;
	        
	        // Recupera o menu que foi clicado
	        NavDrawerItem item = menu[position];
	        
	        // Aciona o fragmento correto
	        switch(item.getId()){
	        case IMenuDrawerConstants.MENU_ITEM_CATEGORIAS:
	        	frag = new CategoriaActivity();
	        	break;
	        case IMenuDrawerConstants.MENU_ITEM_CONTAS:
	        	frag = new ContaActivity();
	        	break;
	        case IMenuDrawerConstants.MENU_ITEM_DESPESAS:
	        	frag = new DespesaActivity();
	        	break;
	        case IMenuDrawerConstants.MENU_ITEM_GRUPOS:
	        	frag = new GrupoActivity();
	        	break;
	        case IMenuDrawerConstants.MENU_ITEM_RECEITAS:
	        	frag = new ReceitaActivity();
	        	break;
	        case IMenuDrawerConstants.MENU_ITEM_TRANSFERENCIA:
	        	frag = new TransferenciaActivity();
	        	break;
	        default:
	        	return;
	        }
	        	        	        
	        // Muda o fragmento dinamicamente
	        ft.replace(R.id.content_frame, frag).commit();
	        // Fecha o navegador
	        mDrawerLayout.closeDrawer(mDrawerList);
	    }
	}

}
